﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using System.Diagnostics;

namespace Algorithms.Expressions
{
    public class UnaryExpressionFactory : IExpressionFactory
    {
        #region Fields 

        private readonly string _name;
        private readonly Func<Expression, Expression> _expressionBuilder;

        #endregion // Fields 

        #region Constructor 

        public UnaryExpressionFactory(string name, Func<Expression, Expression> expressionBuilder)
        {
            if (string.IsNullOrEmpty(name))
                throw new ArgumentException("name");
            if (expressionBuilder == null)
                throw new ArgumentException("expressionBuilder");

            _name = name;
            _expressionBuilder = expressionBuilder;
        }

        #endregion // Constructor 

        #region Properties

        public int RequiredArgumentLength { get { return 1; } }

        public string Name
        {
            get { return _name; }
        }

        #endregion // Properties

        #region Methods 

        public Expression Create(IEnumerable<Expression> arguments)
        {
            Debug.Assert(arguments.Count() == RequiredArgumentLength);

            Expression argument = arguments.First();

            return CreateUnary(argument);
        }

        protected virtual Expression CreateUnary(Expression arg)
        {
            return _expressionBuilder(arg);
        }

        #endregion // Methods
    }
}
